<template>
    <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form label-width="auto" :model="paramsForm" >
                    <el-form-item label="开始时间" size="small">
                        <el-date-picker
                            v-model="paramsForm.begindate"
                            type="datetime"
                            placeholder="选择开始日期时间"
                            size="small"
                            :default-time="defaultTime"
                            :value-on-clear="''"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                    <el-form-item label="结束时间" size="small">
                        <el-date-picker
                            v-model="paramsForm.enddate"
                            type="datetime"
                            placeholder="选择结束日期时间"
                            size="small"
                            :default-time="defaultTime"
                            :value-on-clear="''"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                    <el-form-item label="站点" size="small">
                        <el-select v-model="paramsForm.station" placeholder="请选择站点" size="small"
                            style="width: 150px" @visible-change="getStations">
                            <el-option v-for="item in stationsArr" :label="item.DESCRIPTION" 
                                :value="item.DESCRIPTION" :key="item.DESCRIPTION" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getDatas(paramsForm)"
                            :loading="loading">查询</el-button>
                        </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow" :permObj="permObj"
                @addClick="editDatas('add', {})" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(newDatasArr, 'basTable', 'BAS信息')"
                @downloadExcelAll="downloadExcelAll(datasArr, 'BAS信息')" @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel', selectRows)" @batchUpload="batchUpload">
            </Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage"
                v-model:pageSize="pageSize"
                @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)"
                @toFirst="toFirstPage"
                @toEnd="toEndPage"
                @toSpecify="toSpecifyPage"
                @changePsize="changePageSize"
            ></Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%"  v-loading="loading" 
                @selection-change="handleSelectionChange"
                id="basTable"
            >
                <el-table-column type="selection" width="50" v-if="selectShow"/>
                <el-table-column fixed prop="BDATE" label="日期" width="110" >
                    <template #default="{row}">
                        {{ dateFormat(row.BDATE) }}
                    </template>
                </el-table-column>
                <el-table-column fixed prop="BTIME" label="时间" width="70" />
                <el-table-column prop="CNAME" label="设备名称" width="180" />
                <el-table-column prop="ENAME" label="设备号" width="120" />
                <el-table-column prop="DESCRIPTION" label="内容" width="120" />
                <el-table-column prop="VALUE" label="值" width="70" />
                <el-table-column prop="UNIT" label="单位" width="70" />
                <el-table-column prop="STATION" label="站点" width="120" />
                <el-table-column prop="DATE_TIME" label="事件时间" width="180" >
                    <template #default="{row}">
                        {{ dateFormatTimeStamp(row.DATE_TIME) }}
                    </template>
                </el-table-column>                       
                <el-table-column fixed="right" label="Operations" min-width="60"
                    width="210"
                    v-perm="permObj.update"
                >
                    <template #default="{row}"> 
                        <el-button type="warning" size="small" @click="editDatas('copy', row)" title="复制"
                            v-perm="permObj.add">
                            <el-icon>
                                <CopyDocument />
                            </el-icon>
                        </el-button>                          
                        <el-button  type="danger" size="small" class="del" title="删除" 
                            @click="editSubmit('delete',row)"
                            v-perm="permObj.delete"
                        >
                            <el-icon><DeleteFilled /></el-icon>
                        </el-button>
                    </template>
                </el-table-column>               
            </el-table>
        </template>
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" @submit="editSubmit(submitType, editForm)"
        @cancel-submit="resetForm">
        <el-form :model="editForm" ref="updateFormRef" :rules="rules">
            <el-form-item label="日期" :label-width="formLabelWidth" prop="BDATE">
                <el-date-picker v-model="editForm.BDATE" type="date" placeholder="请选择日期" format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="时间" :label-width="formLabelWidth" prop="BTIME">
                <el-input v-model="editForm.BTIME" autocomplete="off" />
            </el-form-item>
            <el-form-item label="设备名称 " :label-width="formLabelWidth" prop="CNAME">
                <el-input v-model="editForm.CNAME" autocomplete="off" />
            </el-form-item>
            <el-form-item label="设备号 " :label-width="formLabelWidth" prop="ENAME">
                <el-input v-model="editForm.ENAME" autocomplete="off" />
            </el-form-item>
            <el-form-item label="内容" :label-width="formLabelWidth" prop="DESCRIPTION">
                <el-input v-model="editForm.DESCRIPTION" autocomplete="off" />
            </el-form-item>
            <el-form-item label="值" :label-width="formLabelWidth" prop="VALUE">
                <el-input v-model="editForm.VALUE" autocomplete="off" />
            </el-form-item>
            <el-form-item label="单位" :label-width="formLabelWidth" prop="UNIT">
                <el-input v-model="editForm.UNIT" autocomplete="off" />
            </el-form-item>
            <el-form-item label="站点" :label-width="formLabelWidth" prop="STATION">
                <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                    <el-select v-model="editForm.STATION" clearable placeholder="请选择站点" style="width: 150px"
                        @visible-change="getStations">
                        <el-option v-for="item in stationsArr" :label="item.DESCRIPTION" 
                                :value="item.DESCRIPTION" :key="item.DESCRIPTION" />
                    </el-select>
                </el-config-provider>
            </el-form-item>
            <el-form-item label="事件时间" :label-width="formLabelWidth" prop="DATE_TIME">
                <el-date-picker v-model="editForm.DATE_TIME" type="datetime" placeholder="请选择事件时间" format="YYYY/MM/DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
        </el-form>
    </Drawer>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys" @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate', uploadTable)" @batchAdd="editSubmit('batchAdd', uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table', 'BAS信息导入模板')">
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <el-table-column fixed prop="BDATE" label="日期" width="120" />
            <el-table-column prop="BDATE" label="日期" width="110" >
                <template #default="{row}">
                    {{ dateFormat(row.BDATE) }}
                </template>
            </el-table-column> 
            <el-table-column fixed prop="BTIME" label="时间" width="70" />
            <el-table-column prop="CNAME" label="设备名称" width="180" />
            <el-table-column prop="ENAME" label="设备号" width="120" />
            <el-table-column prop="DESCRIPTION" label="内容" width="120" />
            <el-table-column prop="VALUE" label="值" width="70" />
            <el-table-column prop="UNIT" label="单位" width="70" />
            <el-table-column prop="STATION" label="站点" width="120" />
            <el-table-column prop="DATE_TIME" label="事件时间" width="180" >
                <template #default="{row}">
                    {{ dateFormatTimeStamp(row.DATE_TIME) }}
                </template>
            </el-table-column>          
        </el-table>
    </Dialog>
</template>

<script setup>
import {ref, reactive } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue';
import Paging from '@/components/Paging.vue'
import Control from '@/components/Control.vue'
import Drawer from '@/components/Drawer.vue'
import Dialog from '@/components/Dialog.vue'
import { amddStore } from '@/stores/amddStore';
import { paging } from '@/utils/paging'
import { getStationsInfo, getBasDataInfo, editBasData, batchEditBasData } from '@/utils/autoMationDevDataApi/basData'
import { msgOpen } from '@/utils/msg'
import { dateFormat,dateFormatTimeStamp } from '@/utils/dateFormat'
import { exportClickFromTableId , exportClickFromDatas } from '@/utils/downloadExcel'
import { confirm, confirmBatch } from '@/utils/confirm'
import { objCopy } from '@/utils/objCopy'

//权限对象--用于控制按钮显示
const permObj = {
    add: { name: 'BasData', type: 'add' },
    update: { name: 'BasData', type: 'update' },
    delete: { name: 'BasData', type: 'delete' }
}

//实例化amddStore
const useAmddStore = amddStore()

//查询
//#region 
const {
    datasArr,
    datasLength,
    firstPage,
    pageSize,
    countPage,
    newDatasArr,
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页

// loading状态
let loading = ref(false);

//查询参数表单对象
const paramsForm = reactive({
    begindate: "",
    enddate: "",
    station: "",
})

//默认时间
const defaultTime = new Date()

//站点列表
const stationsArr = ref([])
//获取站点列表
const getStations = async () => {
    if(!useAmddStore.stations.length){
        let res = await getStationsInfo()
        // console.log(res)
        if(res.status){
            useAmddStore.setStations(res.resDatas.stations)
        }
    }else{
        stationsArr.value = useAmddStore.stations
    }
}

//获取标签值列表
const getDatas = async (form) => {
    // console.log(form)
    loading.value = true
    let res = await getBasDataInfo(form)
    // console.log(res)
    if(res.resStatus){
        pagingPreprocessing(res.resDatas.basDataInfo)
    }else{
        msgOpen(res.resMsg)
    }
    // pagingPreprocessing(res.resDatas.basDataInfo) //分页前置处理
    loading.value = false
}


//#endregion

//编辑
//#region 
let title = ref("")
let size = ref("40%")
let formLabelWidth = ref("110")
let drawerRef = ref(null) //组件ref

//编辑信息
let oldLbValue = reactive({
    BDATE: '',
    BTIME: '',
    CNAME: '',
    ENAME: '',
    DESCRIPTION: '',
    VALUE: '',
    UNIT: '',
    STATION: '',
    DATE_TIME: '',
})
let editForm = reactive({
    BDATE: '',
    BTIME: '',
    CNAME: '',
    ENAME: '',
    DESCRIPTION: '',
    VALUE: '',
    UNIT: '',
    STATION: '',
    DATE_TIME: '',
})
//提交类型
let submitType = ref('')
//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    BDATE: [
        { required: true, message: '请选择日期', trigger: 'change' }
    ],
    BTIME: [
        { required: true, message: '请输入时间', trigger: 'blur' }
    ],
    CNAME: [
        { required: true, message: '请输入设备名称', trigger: 'blur' }
    ],
    ENAME: [
        { required: true, message: '请输入设备号', trigger: 'blur' }
    ],
    DESCRIPTION: [
        { required: true, message: '请输入描述', trigger: 'blur' }
    ],
    VALUE: [
        { required: true, message: '请输入值', trigger: 'blur' }
    ],
    // UNIT: [
    //     { required: true, message: '请输入单位', trigger: 'blur' }
    // ],
    STATION: [
        { required: true, message: '请选择站点', trigger: 'change' }
    ],
    DATE_TIME: [
        { required: true, message: '请选择事件时间', trigger: 'change' }
    ],
})

//重置表单
const resetForm = () => {
    if (submitType.value === 'update' || submitType.value === 'copy') {
        editForm = objCopy(oldLbValue, editForm)
    } else if (submitType.value === 'add') {
        editForm = reactive({
            BDATE: '',
            BTIME: '',
            CNAME: '',
            ENAME: '',
            DESCRIPTION: '',
            VALUE: '',
            UNIT: '',
            STATION: '',
            DATE_TIME: '',
        })
    }
}

/**
 * 处理单个设备编辑、删除
 * @param type 操作类型，add：新增，update：编辑，del：删除
 * @param row 
 */
const editDatas = (type, row) => {
    // console.log(type)
    // console.log(row)
    submitType.value = type
    if (type === 'add') {
        drawerRef.value.open()
        title.value = "新增"
        resetForm()
    }
    if (type === "copy") {
        drawerRef.value.open()
        title.value = "复制"
        editForm = objCopy(row, editForm)
        editForm.BDATE = dateFormat(row.BDATE)
        editForm.BTIME = row.BTIME
        editForm.CNAME += "_副本"
        editForm.ENAME = row.ENAME
        editForm.DESCRIPTION = row.DESCRIPTION
        editForm.VALUE = row.VALUE
        editForm.UNIT = row.UNIT.length ? row.UNIT : ""
        editForm.STATION = row.STATION
        editForm.DATE_TIME = dateFormatTimeStamp(row.DATE_TIME)
    }
    /*if (type === 'update') {
        drawerRef.value.open()
        title.value = "编辑"
        editForm = row
        editForm.CREATEDATE ? editForm.CREATEDATE = dateFormat(row.CREATEDATE) : ''
        editForm.OUTPUTDATE ? editForm.OUTPUTDATE = dateFormat(row.OUTPUTDATE) : ''
        editForm.SIGNDATE ? editForm.SIGNDATE = dateFormat(row.SIGNDATE) : ''
        editForm.PRODUCTDATE ? editForm.PRODUCTDATE = dateFormat(row.PRODUCTDATE) : ''
        editForm.SCHEDREDATE ? editForm.SCHEDREDATE = dateFormat(row.SCHEDREDATE) : ''
        //存储未修改前用户信息
        oldLbValue = objCopy(row, oldLbValue)
    }*/
}

//#endregion

//批量处理
//#region 
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectRows = ref([]) //选中的设备行数据
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "BDATE",
    "BTIME",
    "CNAME",
    "ENAME",
    "DESCRIPTION",
    "VALUE",
    "UNIT",
    "STATION",
    "DATE_TIME"
]) //上传的字段

const batchEdit = () => {
    if (newDatasArr.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}

/**
 * 表格选中行数据变化时触发的方法
 * @param val 选中的设备行数据
 */
const handleSelectionChange = (val) => {
    val.forEach(item => {
        item.BDATE = dateFormat(item.BDATE)
        item.DATE_TIME = dateFormatTimeStamp(item.DATE_TIME)
    })
    selectRows.value = val
}

//批量上传
let uploadTable = ref([])
const batchUpload = () => {
    // console.log('batchUpload');
    dialogRef.value.open()
}

//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e) => {
    // console.log(e.value)            
    uploadTable = e.value
}

//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = () => {
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data, tableId, fileName) => {
    data.length ? exportClickFromTableId(tableId, fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data, fileName) => {
    if (data.length) {
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝      
        exportClickFromDatas(newData, fileName)
    } else {
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
const downloadTemplate = (tableId, fileName) => {
    // console.log(tableId)
    exportClickFromTableId(tableId, fileName)
}

//#endregion


/**
 * 处理值编辑、删除、批量操作
 * @param type 操作类型，batchDel：批量删除
 * @param data 选中的值数据
 * 
 */
const editSubmit = async (type, data) =>{
    // console.log(type)
    // console.log(data)
    if(type === "add" || type === "copy"){
         updateFormRef.value.validate(async (valid) => {
            if (!valid) {
                return false
            } else {
                let res = await editBasData(type, data)
                // console.log(res)
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                res.resStatus ? msgOpen(res.resMsg, 'success') : msgOpen(res.resMsg)
                getDatas(paramsForm)
                resetForm()
            }
        })
    }
    if (type === 'delete') {
        let resConfirm = await confirm(`确认删除${data.DATE_TIME},${data.STATION}${data.ENAME}${data.DESCRIPTION}的数据吗？`)
        if (resConfirm) {
            data.BDATE = dateFormat(data.BDATE)
            data.DATE_TIME = dateFormatTimeStamp(data.DATE_TIME)
            let res = await editBasData(type, data)
            res.resStatus ? msgOpen(res.resMsg, 'success') : msgOpen(res.resMsg)
            getDatas(paramsForm)
        }
    }
    if(type === "batchAdd" || type === "batchUpdate"){
        let res = await batchEditBasData(type,data)
        dialogRef.value.close()
        uploadTable = ref([])
        res.resStatus ? msgOpen(res.resMsg,'success') : msgOpen(res.resMsg)
        getDatas(paramsForm) 
    }   
    if (type === 'batchDel') {
        if (!data.length) {
            msgOpen('未进行勾选，请勾选！')
        } else {
            let isDel = await confirmBatch(data.length)
            if (isDel) {  
                let res = await batchEditBasData(type,data)
                // console.log(res)
                if (!res.resStatus) {
                    msgOpen(res.resMsg)
                } else {
                    res.resDatas.result.rowsAffected ? msgOpen(`${res.resMsg},共${res.resDatas.result.rowsAffected}条`, "success")
                        : msgOpen(res.resMsg)
                }
                getDatas(paramsForm)
            }
        }
    }
}

</script>

<style lang="less" scoped>
.params-form {
    height: 100%;
    width: 100%;

    .el-form {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .el-form-item {
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }
}

.el-table {
    height: 95%;
}

</style>